<?php
namespace App\Libs\Captcha\Algorithms;
class Arithmetic extends \App\Libs\Base\Singleton implements AlgorithmInterface
{
    public function generate($length = 0) {
        $r = mt_rand(0, 100);
        switch($r%4) {
        case 0:
            $res = $this->plus();
            break;
        case 1:
            $res = $this->minus();
            break;
        case 2:
            $res = $this->mul();
            break;
        case 3:
            $res = $this->div();
            break;
        default:
            $res = $this->plus();
            break;
        }
        return $res;
    }

    protected function div() {
        $a = mt_rand(1, 9);
        $b = mt_rand(1, 9);

        $t = mt_rand(0, 100);
        if ($t < 50) {
            return array(
                'captcha' => ($a * $b) . '÷' . $b . '=?',
                'check' => $a,
            );
        } else {
            return array(
                'captcha' => '?*' . $b . '=' . ($a * $b),
                'check' => $a,
            );
        }
    
    }

    protected function mul() {
        $a = mt_rand(1, 9);
        $b = mt_rand(1, 9);

        $t = mt_rand(0, 100);
        if ($t < 50) {
            return array(
                'captcha' => $a . '*' . $b . '=?',
                'check' => $a * $b,
            );
        } else {
            return array(
                'captcha' => '?÷' . $b . '=' . $a,
                'check' => $a * $b,
            );
        }
    } 

    protected function minus() {
        $a = mt_rand(1, 9);
        $b = mt_rand(0, 9);

        $t = mt_rand(0, 100);
        if ($t < 50) {
            return array(
                'captcha' => ($a + $b) . '-' . $b . '=?',
                'check' => $a,
            );
        } else {
            return array(
                'captcha' => '?+' . $b . '=' . ($a + $b),
                'check' => $a,
            );
        }
    }

    protected function plus() {
        $a = mt_rand(1, 9);
        $b = mt_rand(0, 9);

        $t = mt_rand(0, 100);
        if ($t < 50) {
            return array(
                'captcha' => $a . '+' . $b . '=?',
                'check' => $a + $b,
            );
        } else {
            return array(
                'captcha' => '?-' . $a . '=' . $b,
                'check' => $a + $b,
            );
        }
    } 
}
